#!/bin/sh

# 安装mobileprovision
function installMobileProvision() {
    # 需要的参数
    mobileprovision_path=$1 #"/Users/admin/Desktop/wk/zg/com.luomo.ryzg.apple_dev.mobileprovision"
    profile_path="/Users/admin/Library/MobileDevice/Provisioning Profiles"
    option_plist_path="$profile_path"/option.plist

    if [[ ! -d "$profile_path" ]]; then
        echo "Profiles目录不存在"
        exit 1
    fi

    # 判断文件是否以.mobileprovision结尾
    if [[ "$mobileprovision_path" == *.mobileprovision ]]; then
        security cms -D -i "$mobileprovision_path" >"$option_plist_path"
    else
        echo "mobileprovision文件不存在"
        exit 1
    fi

    # 从plist文件中获取UUID作为新文件名称
    if [[ -f "$option_plist_path" ]]; then
        uuid=$(/usr/libexec/PlistBuddy -c "Print UUID" "${option_plist_path}")
    fi

    cp "${mobileprovision_path}" "${profile_path}/${uuid}.mobileprovision"
    rm -rf "${option_plist_path}"
    echo "1 mobileprovision imported"
}

# 安装p12
function installP12() {
    mac_password="yunmiao"
    p12_password=$2 #"123123"
    p12_path=$1 #"/Users/admin/Desktop/wk/zg/com.luomo.ryzg.apple_dev.p12"

    if [[ ! $p12_path == *.p12 ]]; then
        echo "该文件不是p12文件"
        exit 1
    fi

    # 电脑解锁
    security unlock-keychain -p ${mac_password} /Users/$(whoami)/Library/Keychains/login.keychain
    # 证书导入
    security import "${p12_path}" -k /Users/$(whoami)/Library/Keychains/login.keychain -P ${p12_password} -T /usr/bin/codesign
}

##### main程序入口 #####
provision_path=$1

if [[ ! -d $provision_path ]]; then
    echo "证书目录不能为空"
    # exit 1
fi

for file in $(ls ${provision_path}); do
    if [[ $file == *.mobileprovision ]]; then
        installMobileProvision ${provision_path}/${file};
    elif [[ $file == *.p12 ]]; then
        if [[ -z $pw ]]; then
            read -p "请输入证书密码:" pw
        fi
        installP12 ${provision_path}/${file} $pw
    fi
done
